package com.im.chat.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.im.chat.dto.EmojiDto;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @author 作者 :LG
 * @version 创建时间：2016年12月22日 下午3:39:01
 * 类说明:
 */
@SuppressWarnings("unchecked")
public class EmojiUtil {
	public static Map<String, Object> emoji_map=null;

	static {
		emoji_map = new HashMap<String, Object>();

		InputStream is = EmojiUtil.class.getClassLoader().getResourceAsStream(
				"conf/emoji.xml");
		//创建SAXReader对象
		SAXReader reader = new SAXReader();
	        //读取文件 转换成Document
        Document document = null;
		try {
			document = reader.read(is);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		if(null!=document){
			//获取根节点元素对象
			Element root = document.getRootElement();
			Element emoji_hanshu = root.element(EmojiConstant.EMOJI_HANSHU);
			List<Element> emoji_iteams = emoji_hanshu.elements(EmojiConstant.EMOJI_ITEAM);
			for(Element element:emoji_iteams){
				EmojiDto emojiDto = new EmojiDto();
				emojiDto.setId(element.elementText(EmojiConstant.EMOJI_ITEAM_ID));
				emojiDto.setFile(element.elementText(EmojiConstant.EMOJI_ITEAM_FILE));
				emojiDto.setTag(element.elementText(EmojiConstant.EMOJI_ITEAM_TAG));
				emoji_map.put(emojiDto.getTag(), emojiDto);
			}
		}
	}

	public static EmojiDto getEmojiFileByTag(String tag){
		return (EmojiDto) emoji_map.get(tag);
	}

	public static String transEmoji(String str,String imaPath){
		Pattern pattern = Pattern.compile(EmojiConstant.EMOJI_PATTERN);
		Matcher matcher = pattern.matcher(str);
		while(matcher.find()){
			String emojitag= matcher.group();
			EmojiDto emojiDto = getEmojiFileByTag(emojitag);
			if(null!=emojiDto){
				String imaReplease=EmojiConstant.EMOJI_IMAGE_STR.replace(EmojiConstant.EMOJI_IMAGE_STR_RE, imaPath+"/"+emojiDto.getFile());
				str=str.replace(emojitag, imaReplease);
			}else{
				return str;
			}
			matcher = pattern.matcher(str);
		}
		return str;
	}

	public static void main(String args[]) {
//		initXML();
		String str = "aaaaaa[emoji_006]aaaaaaaaa[emoji_007]aaaaaa[emoji_006]aaa[emoji_009]aaaa[emoji_010]aa";

		System.out.println(transEmoji(str,"ad/news/"));
	}




}
